(ns tws.client.twsclient
  (:import (com.ib.client EClientSocket Contract))
  (:require [wrapper.ewrapperimpl])
  ;"require should come before import for def record imports"
  (:import [wrapper.ewrapperimpl Ewrapperimpl])
  (:use [clojure.tools.logging :only (info error)])
  (:use constants.constants)

  )

(defn connect
  ([wrapper] (connect wrapper "localhost" 7496 1))
  ([wrapper host] (connect wrapper host 7496 1))
  ([wrapper host port] (connect wrapper port 1))
  ([wrapper host port client-id]
    (let [connection (EClientSocket. wrapper)]
      (println "connecting to " host "port" port "clientid" client-id)
      (doto connection
        (.eConnect host port client-id)
        (.setServerLogLevel 5)
        (.reqCurrentTime))))
  )


(defn make-contract
  ([securityName secType exchange expiry m_right multiplier primaryExch currency]
  (let [c (Contract.)]
    (set! (.m_symbol c) securityName)
    (set! (.m_secType c) secType)
    (set! (.m_exchange c) exchange)
    (set! (.m_expiry c) expiry)
    (set! (.m_right c) m_right)
    (set! (.m_multiplier c) multiplier)
    (set! (.m_currency c) currency)
    (set! (.m_primaryExch c) primaryExch)
    c
    )
    )
  (
    [securityName]
    (make-contract securityName "STK" "SMART" "" "" "" "" "USD")
  )
  )

(defn request-market-data
  ([connection id contract tick-list]
    (info "requesting market data " (.toXML xstreamInstance contract))
    (.reqMktData connection id contract tick-list false)
    id
    )

  ([connection id contract]
    (.reqMktData connection id contract "" false)
    id)
  )

(defn disconnect
  [connection]
  (.eDisconnect connection))

;default lis of contracts 
;; modify using assoc
(def contracts {:1 (make-contract "BAC")
                :2 (make-contract "IBN")
                :3 (make-contract "IBN")
                }
  )
